package com.techblor.library.wechat.api.officialaccount;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 微信服务器接入配置接口
 */
@Slf4j
public class ServerAccessApi {

    /**
     * 验证服务器
     * 将传入的token ,timestamp, nonce按照字典顺序进行排序
     *
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);
        StringBuilder sb = new StringBuilder();
        for (String str : strArray) {
            sb.append(str);
        }

        return sb.toString();
    }

    /**
     * 将传入的token,timestamp,nonce按照字典顺序进行排序后进行加密
     *
     * @param value
     * @return
     */
    public static String encryt(String value) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(value.getBytes());
            byte[] messageDigest = digest.digest();

            // 创建十六进制字符串
            StringBuffer hexString = new StringBuffer();

            // 字节数组转换为十六进制数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("加密方式出错");
            e.printStackTrace();
        }

        return "";
    }


}
